<?php
/**
 * Token Service
 * User: zng
 * Date: 2019/11/4
 * Time: 15:07
 */
namespace other;

use app\exceptions\OrdinaryException;
use think\File;
use think\Image;

/**
 * 图片上传类
 * @tips 各个平台的上传服务用upload_开头
 * @package other\Uploader
 */
Class Uploader {

    /**
     * 本地图片上传服务
     * @param \think\File
     * @param
     * @return false|string
     */
    public function upload_local( File $file, string $type='image' )
    {
        $config = config('files.');
        $folder = $config['local']['folder'].'/'.$type;
        $info = $file->validate([
            'ext' => config('files.ext.'.$type)
        ])->move($folder);
        if ( ! $info ) {
            return false;
        }
        if ( $type === 'image' ) {
            $this->generateThumb($info, $config['local']['thumb']);
        }
        //返回完整路径,方便图片的迁移或者更改图片上传的平台
        return request()->domain().'/'.$folder.'/'.str_replace('\\','/', $info->getSaveName());
    }

    /**
     * 七牛云上传服务
     * @param \think\File
     * @return false|string
     */
    public function upload_qiniu( File $file, string $type='image' )
    {
        $config = config('files.qiniu');
        return $config['domain'].app('uploader_service')->upload($file, $type);
    }

    /**
     * 缩略图生成
     * @param string|\think\File $file
     * @param array $config 缩略图配置
     * @throws OrdinaryException
     * @return void
     */
    public function generateThumb( $file, array $config ):void
    {
        if ( !isset($config['path']) || $config['path'] === false || !isset($config['size']) || $config['size'] === false ) {
            return;
        }
        $thumb_path = str_replace('\\','/', $file->getSaveName());
        foreach ( $config['size'] as $_size ) {
            $file_path = './'.$config['path'].'/'.$_size[0].'/'.$_size[1].'/'.$thumb_path;
            $folder_path = dirname($file_path);
            if ( is_dir($folder_path) === false ) {
                if ( mkdir($folder_path, 0755, true) === false ) {
                    throw new OrdinaryException('文件夹['.$folder_path.']创建失败,请手动创建文件夹路径');
                }
            }
            $image = Image::open($file);
            $image->thumb( $_size[0], $_size[1] )->save($file_path);
        }
    }

    /**
     * 获取缩略图
     * @param string $filepath 原图网络地址
     * @param int $key 配置文件尺寸参数的key
     * @return string $thumbPath or $filepath
     */
    public function thumbPath( string $filepath, int $key=0 ):string
    {
        $config = config('files.');
        if ( $config[$config['type']]['thumb'] === false || !isset($config[$config['type']]['thumb']['size'][$key]) ){
            return $filepath;
        }
        $thumbpath = $config[$config['type']]['thumb']['path'];
        $thumbsize = $config[$config['type']]['thumb']['size'][$key];
        $relativepath = './'.str_replace( $config[$config['type']]['folder'].'/images',
                $thumbpath.'/'.$thumbsize[0].'/'.$thumbsize[1],
                substr($filepath, strpos($filepath, $config[$config['type']]['folder'])) );
        if ( file_exists( $relativepath ) ) {
            return str_replace($config[$config['type']]['folder'].'/images',
                $thumbpath.'/'.$thumbsize[0].'/'.$thumbsize[1],
                $filepath);
        }
        return $filepath;
    }

    /**
     * 检测文件是否存在本地
     * @param string $filepath 文件网络地址
     * @return bool
     */
    public function checkFiles( string $filepath ):bool
    {
        if ( strpos($filepath,request()->domain()) === false ) {
            return true;
        }
        return file_exists('.'.str_replace(request()->domain(), '', $filepath));
    }

}